import './TeacherVideoPage.scss';
import { DoubleLeftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import PlayListItem from './componets/PlayListItem/PlayListItem';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect, useState } from 'react';
import { fetchGetVideoList } from '@/store/modules/teacher';
import { getVideoAPI } from '@/apis/teacher';


export default function TeacherVideoPage() {


    const dispatch = useDispatch();
    const navigate = useNavigate();
    const { user_status } = useSelector(state => state.user);
    const { videoList } = useSelector(state => state.teacher);
    const [videoSrc, setVideoSrc] = useState(null);

    useEffect(() => {
        async function getVideoList() {
            if (videoList.length === 0) {
                await dispatch(fetchGetVideoList(user_status.class_id, user_status.token));
            }
        }

        getVideoList();

        const filename = user_status.video_url.split('=')[1];

        async function getVideo() {
            console.log(filename);

            const res = await getVideoAPI({
                filename,
                class_id: user_status.class_id
            }, user_status.token)

            
            const videoURL = URL.createObjectURL(res.data);
            setVideoSrc(videoURL);
        }


        getVideo();

    }, [])

    function backToVideoList() {
        navigate('/teachercourse');
    }


    return (
        <div className="TeacherVideoPage">
            <header>
                <button onClick={backToVideoList}>
                    <DoubleLeftOutlined />
                    返回
                </button>
                <div>
                    <h1>{user_status.video_url.split('=')[1]}</h1>
                    <span>{user_status.classname}</span>
                </div>
            </header>
            <main>
                <video controls>
                    {videoSrc && <source
                        src={videoSrc}
                        type="video/mp4"
                    />}
                </video>
            </main>
            <ul>
                {videoList.map(
                    (ele, index) => <PlayListItem key={index} itemInfo={ele} />
                )}
            </ul>

        </div>
    )
}